# -*- coding: utf-8 -*-
# בש״ד
#
# Teniente Django Template Slots - Part of the Cuba Libre Project
# Copyright (C) 2009, Joshua "jag" Ginsberg <jag@flowtheory.net>
# 
# Para mi amor, que inspira a mi cada respiración y que extraña a Cuba
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

import sys
from django import template
from django.conf import settings
from teniente import api

def debug(*args):
    if settings.TEMPLATE_DEBUG:
        sys.stderr.write(' '.join(map(str, args))+'\n')

register = template.Library()
class SlotNode(template.Node):
    def __init__(self, slot_id):
        self.slot_id = slot_id
    
    def render(self, context):
        slot_component = api.ITemplateSlot.get_component_by_id(self.slot_id)
        if not slot_component:
            raise template.TemplateSyntaxError(
                u'No slot registered with id %s' % self.slot_id)
        try:
            component_data = api.ITemplateSlotToken.get_registered_components()
            token_components = map(
                lambda tpl: api.ITemplateSlotToken.get_component_by_id(tpl[0]),
                component_data)
            debug('Token components', token_components)
            debug(self.slot_id, self.slot_id.__class__)
            component_list = filter(lambda c: c.get_slot_id() == self.slot_id,
                                    token_components)
            debug('Component list', component_list)
            if not component_list:
                return u''
            token_list = map(lambda c: c.render_token(context),
                             component_list)
            debug('Token list', token_list)
            # filter out empty tokens
            token_list = filter(lambda token: token.strip(), token_list)
            rendered_token_list = map(
                lambda token: slot_component.wrap_token(token),
                token_list)
            return slot_component.render_slot(rendered_token_list)
        except Exception, e:
            if settings.DEBUG:
                raise
            else:
                return u''

@register.tag(name='define_slot')
def do_define_slot(parser, token):
    try:
        tag_name, slot_id = token.split_contents()
    except ValueError:
        raise template.TemplateSyntaxError(
            u'syntax {% define_slot component_id %}')
    return SlotNode(slot_id)
